package cn.tl.base.service.impl;

import cn.tl.base.service.ICodeService;
import cn.tl.utils.SendMsgUtils;
import cn.tl.utils.StrUtils;
import com.mysql.jdbc.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendCode(Map<String, String> map) throws Exception{
        //获取请求参数
        String phone = map.get("phone");
        String codeType = map.get("codeType");
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone+":"+codeType);
        String code = StrUtils.getRandomString(6);
        if (codeInRedis!=null){
           Long pretime = Long.valueOf(codeInRedis.split(":")[1]);
           if(System.currentTimeMillis()-pretime<60*1000){
               throw new Exception("发送过于频繁,请稍候再试");
           }else {
               code = codeInRedis.split(":")[0];
           }
        }

        /*System.out.println(phone);
        System.out.println(codeType);*/
        SendMsgUtils.sendCode(phone,code);
        System.out.println("本次验证码为"+ code);
        //把code放在redis
        redisTemplate.opsForValue().set(phone+":"+codeType,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);

    }
}
